package com.css.bjdt_core.report.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.css.bjdt_core.report.entity.RptGroup;
import com.css.bjdt_core.report.entity.RptTemplate;
import com.css.bjdt_core.util.CommonUtil;

@Service
public class ReportGroupManageService {
	@Autowired
	private Dao dao;

	@Autowired
	private ReportTemplateManageService reportTemplateManageService;

	/**
	 * 新增套表
	 * @param record
	 * @return
	 */
	public RptGroup insertRptGroup(RptGroup rptGroup) {
		if (StringUtils.isEmpty(rptGroup.getGroupId())) {
			rptGroup.setGroupId(CommonUtil.getUUID());
		}
		return dao.insert(rptGroup);
	}

	/**
	 * 根据id查询相关套表信息
	 * @param id
	 * @return
	 */
	public RptGroup queryByID(String id) {
		return dao.fetch(RptGroup.class, id);
	}

	/**
	 * 更新套表
	 * @param rptGroup
	 * @return
	 */
	public int update(RptGroup rptGroup) {
		return dao.updateIgnoreNull(rptGroup);
	}

	/**
	 * 删除套表
	 * @param groupId
	 * @return
	 */
	public void deleteGroup(String groupId, String annualId) {
		//先删子表
		List<RptTemplate> rptTemplateList = dao.query(RptTemplate.class, Cnd.where("GROUPID", "=", groupId));
		for (RptTemplate rptTemplate : rptTemplateList) {
			reportTemplateManageService.deleteAnRptTemplate(rptTemplate.getTemplateId(), annualId);
		}
		//再删套表
		dao.clear(RptGroup.class, Cnd.where("GROUPID", "=", groupId));
	}

	/**
	 * 查询所有套表
	 * @return
	 */
	public List<RptGroup> queryRptGroupList(String annualId) {
		return dao.query(RptGroup.class, Cnd.where("ANNUALID", "=", annualId).asc("ORDERID"));
	}
	
	/**
	 * 查询某党组织已上报的所有套表
	 * @return
	 */
	public List<RptGroup> queryReportedRptGroupList(String annualId, String dzzId) {
		Map<String, String> map = new HashMap<String, String>();
		/*
		 * 如果日后查看审核通过的报表，也需要此功能，
		 * 则下面report_state字符串里加'3';
		 * 如果查看审核退回的报表也需要，则字符串里加'100'
		 */
		map.put("report_state", "'1','2'"/* '3','100' */);
		map.put("dzzId", dzzId);
		map.put("annualId", annualId);
		Condition c = Cnd
				.wrap("exists(select 1 from view_unit_template u "
						+ "left join rpt_batch b on u.batch_id=b.batch_id "
						+ "left join rpt_batch_dzz_r r on b.batch_id=r.batch_id "
						+ "where b.report_state in (${report_state}) and r.ddz_id='${dzzId}' "
						+ "and u.GROUP_ID=GROUPID) "
						+ "and annualId='${annualId}'", map);
		return dao.query(RptGroup.class, c);
	}
}
